package com.tfswx.jcyw.ruleenginedesigner.intercepter;

import com.tfswx.jcyw.ruleenginedesigner.annotation.NeedLogin;
import com.tfswx.jcyw.ruleenginedesigner.annotation.NotNeedLogin;
import com.tfswx.jcyw.ruleenginedesigner.util.UserManger;
import com.tfswx.ruleengine.database.util.NetworkUtil;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author Ricky
 * @date 2021/1/4
 */
@Slf4j
public class LoginIntercepter implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        String host = NetworkUtil.getHost();
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 类上有needlogin注解
        if (method.getDeclaringClass().isAnnotationPresent(NeedLogin.class)) {
            // 方法有无需登录
            if (method.isAnnotationPresent(NotNeedLogin.class)) {
                return true;
            }
        } else if (!method.isAnnotationPresent(NeedLogin.class)) {
            return true;
        }

        UserManger.UserInfo currentUserInfo = UserManger.getLoginUserInfo(request);
        log.info("当前请求用户：{}, IP:{}", currentUserInfo.getMc(), host);
        return true;
    }
}
